﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Organizer.ViewModel;
using Organizer.Model;
using GalaSoft.MvvmLight.Command;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Phone.Scheduler;

namespace Organizer.Views
{
    public class TaskViewModel : BaseViewModel
    {
        private State status = State.Normal;

        public State Status
        {
            get
            {
                return status;
            }
            set
            {
                status = value;
                NotifyPropertyChanged(() => this.Status);
            }
        }
        
        //таск полоученный для редактирования
        private Task _taskToEdit;
        //временный объект - таск, который редактируется
        private Task _editedTask;

        public TaskViewModel()
        {
            NotifyPropertyChanged(() => this.Tasks);
            //связываем интерфейс команд с конкретными методами
            this.AddCommand = new RelayCommand(() => AddTask());
            this.EditCommand = new RelayCommand<Task>(task => { EditTask(task); });
            this.SaveCommand = new RelayCommand(() => SaveTask());
            this.CancelCommand = new RelayCommand(() => CancelTask());
            //this.CancelSelectionCommand = new RelayCommand(() => CancelSelection());
            //this.ManageCommand = new RelayCommand(() => ManageSelection());
            //this.DeleteOrganizationsCommand = new RelayCommand(() => DeleteOrganizations());
            this.RefreshCommand = new RelayCommand(() => RefreshTasks());
            //this.BackKeyPressCommand = new RelayCommand<CancelEventArgs>(e => BackKeyPressAction(e));
            this.SetRemindCommand = new RelayCommand<Task>(task => { SetRemind(task); });
            Status = State.Normal;
        }

        private void RefreshTasks()
        {
            NotifyPropertyChanged(() => this.Tasks);
        }

        //добавить новый таск
        private void AddTask()
        {
            Status = State.Edit;
            EditedTask = new Task();
            TaskToEdit = new Task();
        }

        //редактировать таск
        private void EditTask(Task task)
        {
            TaskToEdit = task;
            //создаем временный объект
            EditedTask = new Task();
            //копируем свойства во временный объект
            TaskToEdit.Assign(EditedTask);           
            Status = State.Edit;
            NotifyPropertyChanged(() => this.EditedTask);         
        }

        //сохранить таск
        private void SaveTask()
        {
            //копируем свойства временного обекта в оригинальный редактируемый объект            
            EditedTask.Assign(TaskToEdit);            

            if (!string.IsNullOrEmpty(TaskToEdit.Name))
            {
                if (!Tasks.Contains(TaskToEdit))
                {
                    OrganizerDataContext.Instance.Tasks.InsertOnSubmit(TaskToEdit);
                }

                var ttt = OrganizerDataContext.Instance.GetChangeSet();
                OrganizerDataContext.Instance.SubmitChanges();                
                
                Status = State.Normal;
                NotifyPropertyChanged(() => this.Tasks);
            }
            else
            {

            }
        }

        //установить напоминание
        private void SetRemind(Task task)
        {
            Reminder remind;
            var remindName = task.ReminderId.ToString();
            if (ScheduledActionService.Find(remindName) != null)          
                remind = ScheduledActionService.Find(remindName) as Reminder;                             
            else
                remind = new Reminder(remindName);
                            
            remind.Title = task.Name;
            remind.Content = task.Description;
            //r.NavigationUri = new Uri("/ReminderPage.xaml", UriKind.Relative);
            remind.BeginTime = task.TimeStart;                        
            ScheduledActionService.Add(remind);
        }

        /// <summary>
        /// Gets or sets RefreshCommand.
        /// </summary>
        public ICommand RefreshCommand { get; set; }
        
        //отменить редактирование таска
        private void CancelTask()
        {
            Status = State.Normal;
            EditedTask = null;
            OrganizerDataContext.Instance.SubmitChanges();
            NotifyPropertyChanged(() => this.Tasks);
        }

        //Объявление команд
        public ICommand AddCommand { get; set; }
        public ICommand EditCommand { get; set; }
        public ICommand SaveCommand { get; set; }
        public ICommand CancelCommand { get; set; }
        public ICommand SetRemindCommand { get; set; }


        //Объявление свойств
        #region Preperties

        //список тасков
        public List<Task> Tasks
        {
            get { return OrganizerDataContext.Instance.Tasks.ToList(); }
        }

        public List<Man> Men
        {
            get { return OrganizerDataContext.Instance.Mans.ToList(); }
        }

        //таск полоученный для редактирования
        public Task TaskToEdit
        {
            get
            {
                if (_taskToEdit == null)
                {
                    _taskToEdit = new Task();
                }
                return _taskToEdit;
            }
            set
            {
                _taskToEdit = value;
                NotifyPropertyChanged(() => this.TaskToEdit);
            }
        }

        //временный объект - таск, который редактируется
        public Task EditedTask
        {
            get
            {
                if (_editedTask == null)
                {
                    _editedTask = new Task();
                }
                return _editedTask;
            }
            set
            {
                _editedTask = value;
                NotifyPropertyChanged(() => this.EditedTask);
            }
        }

        #endregion
    }
}
